var express = require("express");
var router = express.Router();
const dayjs = require("dayjs");

const authMiddleWare = require("../../middleWare/auth");
const { getResult, updateList, getList } = require("../../utils/sql");

let DATABASE = "weekly_task";
let DATABASE1 = "weekly_task_total";

router.get("/list", authMiddleWare, async function (req, res) {
  let { date, top } = req.query;
  let sql = `SELECT * FROM ${DATABASE} WHERE 1=1 AND user_id=? AND date=?`;
  let paramsList = [req.auth, date];
  if (top || top === 0) {
    sql += ` AND top=?`;
    paramsList.push(top);
  }
  console.log(sql, paramsList);
  let result = await getResult({ sql, paramsList });
  res.send({
    code: 0,
    data: result[0],
    message: "OK",
  });
});

router.post("/add", authMiddleWare, async function (req, res) {
  let { task, date } = req.body;
  let sql = `INSERT INTO ${DATABASE} (task,date,user_id) value(?,?,?)`;
  let paramsList = [task, date, req.auth];

  await getResult({
    sql,
    paramsList,
  });

  res.send({
    code: 0,
    message: "Add Successfully",
  });
});

router.put("/update", authMiddleWare, async function (req, res) {
  let { status, id } = req.body;
  await updateList(DATABASE, ["status"], [status], id);

  res.send({
    code: 0,
    message: "OK",
  });
});

router.put("/top", authMiddleWare, async function (req, res) {
  let { top, id } = req.body;
  await updateList(DATABASE, ["top"], [top], id);

  res.send({
    code: 0,
    message: "OK",
  });
});

router.post("/daily/total", authMiddleWare, async function (req, res) {
  let { date } = req.body;
  let dateList = date.split(" ~ ");
  let sql = `SELECT * FROM daily_task WHERE date BETWEEN ? AND ? AND user_id=?`;
  let paramsList = [...dateList, req.auth];
  let result = await getResult({
    sql,
    paramsList,
  });
  result[0].forEach((item) => {
    item.create_time = dayjs(item.create_time).format("YYYY-MM-DD HH:mm:ss");
  });
  res.send({
    code: 0,
    data: result[0],
    message: "OK",
  });
});

router.get("/summarize", authMiddleWare, async function (req, res) {
  let { date } = req.query;
  getList(DATABASE1, ["date", "user_id"], [date, req.auth]).then((result) => {
    res.send({
      code: 0,
      data: result[0],
      message: "OK",
    });
  });
});

router.post("/summarize", authMiddleWare, async function (req, res) {
  let { date, text, urlList } = req.body;
  let url_list = urlList.join(",");
  let result = await getList(DATABASE1, ["date", "user_id"], [date, req.auth]);
  let sql, paramsList;
  if (result && result.length !== 0) {
    await updateList(
      DATABASE1,
      ["text", "url_list"],
      [text, url_list],
      req.auth,
      "user_id"
    );
  } else {
    sql = `INSERT INTO ${DATABASE1} (user_id,date,text,url_list) value(?,?,?,?)`;
    paramsList = [req.auth, date, text, url_list];
    await getResult({
      sql,
      paramsList,
    });
  }
  res.send({
    code: 0,
    message: "OK",
  });
});

module.exports = router;
